<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <!--	<link rel="shortcut icon" href="../static/favicon.ico" th:href="@{favicon.ico}"/>-->
    <th:block th:include="include :: header('新增商品')"/>
    <th:block th:include="include :: select2-css"/>
    <th:block th:include="include :: bootstrap-select-css"/>
    <style>
        li{
            display:inline
        }
        #basic{
            width: 1040px;
            margin-left: 80px;
        }
        #basic td{
            border-top: 1px solid #dee2e6;
            padding: 6px;
        }
        #basic th{
            border-bottom: 2px solid #dee2e6;
            padding: 12px;
        }
        #specTable{
            width: 530px;
        }
        #specTable td{
            border-top: 1px solid #dee2e6;
            padding: 12px;
        }
        #specTable th{
            border-bottom: 2px solid #dee2e6;
            padding: 12px;
        }
    </style>
</head>
<body>
<div class="main-content">
    <form id="form-TbGoods-add" class="form-horizontal">
        <h4 class="form-header h4">产品信息</h4>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required ">产品名称：</label>
                    <div class="col-sm-8">
                        <input name="productName" placeholder="请输入产品名称" class="form-control valid" type="text" required>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label ">副标题：</label>
                    <div class="col-sm-8">
                        <input name="subtitle" placeholder="请输入商品名称" class="form-control valid" type="text">
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">所属商铺：</label>
                    <div class="col-sm-8">
                        <select name="shopId" class="form-control">
                            <option th:value="${tbShop.shopId}" th:each="tbShop:${tbShops}"
                                    th:text="${tbShop.shopName}">Java
                            </option>
                        </select>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">售后服务：</label>
                    <div class="col-sm-8">
                        <input name="afterservice" class="form-control valid" type="text" value="" required>
                    </div>
                </div>
            </div>
        </div>

        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">所属分类：</label>
                    <input id="treeId" name="categoryId"  type="hidden" th:value="${category.categoryId}"/>
                    <div class="col-sm-8">
                        <div class="input-group">
                            <input placeholder="请选择分类" class="form-control" type="text" onclick="selectCategoryTree()"
                                   id="treeName"  readonly="true"/>
                            <span class="input-group-addon"><i class="fa fa-search"></i></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <input id="templateId" type="hidden" value="">
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">品牌：</label>
                    <div class="col-sm-8">
                        <select id="addGoods-brand" name="brand" class="form-control" required>
                        </select>
                    </div>
                </div>
            </div>
        </div>
        <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">包装列表：</label>
                    <div class="col-sm-8">
                        <input name="packlist" class="form-control valid" type="text" required>
                    </div>
                </div>
            </div>
        </div>
       <!-- <div class="row">
            <div class="col-sm-6">
                <div class="form-group">
                    <label class="col-sm-4 control-label is-required">商品相册：</label>
                    <div class="col-sm-8">
                        <input type="file" name="file" id="doc" multiple="multiple"  style="width:150px;" onchange="javascript:setImagePreviews();" accept="image/*" />
                        <div id="dd" style=" width:990px;"></div>
                    </div>
                </div>
            </div>
        </div>-->
<!-- 在此追加属性-->
        <div id="addGoods-attr">

        </div>
        <h4 class="form-header h4">商品规格</h4>
        <div class="goodList">
        <div class="goods">
        <div class="row">
           <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">基本数据</label>
                        <div class="col-sm-10">
                        </div>
                    </div>
           </div>
        </div>
        <div class="row">
            <table cellspacing="1" id="basic">
                <thead>
                <tr>
                    <th>商品名称</th>
                    <th>供价</th>
                    <th>售价</th>
                    <th>库存</th>
                    <th>状态</th>
                    <th>图片</th>
                </tr>
                </thead>
                <tbody>
                <tr>
                    <td><input name="goodsName" placeholder="请输入商品名称" class="form-control" type="text" style="width: 250px" required></td>
                    <td><input name="costPrice" placeholder="供价" class="form-control" style="width: 100px" type="text" ></td>
                    <td><input name="sellPrice" placeholder="售价" class="form-control" type="text" style="width: 100px" required></td>
                    <td><input name="inventory" placeholder="库存" class="form-control" type="text" style="width: 100px" required></td>
                    <td><select name="status" class="form-control" style="width: 80px">
                        <option value="0">上架</option>
                        <option value="1">下架</option>
                        <option value="2">已删除</option>
                    </select></td>
                    <td><img class="img-thumbnail hidden" name="img" src="" style="float: left;width: 55px;height: 40px;"><input type="file" name="file" style="float: left;width:70px;height:40px;margin-top: 10px;" onchange="setImage(this);" /></td>
                </tr>
                </tbody>
            </table>
        </div>
        <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-2 control-label">规格</label>
                        <div class="col-sm-10">
                        </div>
                    </div>
                </div>
        </div>
        <div class="row">
                <div class="col-sm-6">
                    <div class="form-group">
                        <label class="col-sm-4 control-label is-required">规格录入：</label>
                        <div class="col-sm-8" style="display: flex!important;">
                            <select id="specNameList" class="form-control" style="width: 120px;margin-right: .5rem!important;">
                                <option value="-1">请选择规格值</option>
                            </select>
                            <select id="specValueList" class="form-control" style="width: 120px;margin-right: .5rem!important;">
                                <option value="-1">请选择规格值</option>
                            </select>
                            <button type="button" class="btn btn-primary" id="addSpec" style="width: 100px;margin-right: .5rem!important;" data-toggle="modal" data-target="#exampleModal" data-whatever="规格添加">新建规格</button>
                        </div>
                    </div>
                </div>
        </div>
        </div>
        </div>

    </form>
    <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="exampleModalLabel">Add SpecInfo</h4>
                </div>
                <div class="modal-body">
                    <form>
                        <div class="form-group">
                            <label class="col-sm-3 control-label  is-required">规格名称：</label>
                            <div>
                                <input class="form-control" type="text" id="specName" required>
                            </div>
                        </div>
                        <div class="form-group">
                            <button type="button" class="btn btn-default" id="addSpecValue" data-toggle="button" style="width: 100px;">+添加规格</button>
                        </div>
                        <div class="form-group">
                            <table id="specTable">
                                <thead>
                                <tr>
                                    <th>规格值</th>
                                    <th>操作</th>
                                </tr>
                                </thead>
                                <tbody>
                                <tr>
                                    <td><input class="form-control" type="text" style="width: 250px" name="specValue" value="" required></td>
                                    <td><button alt="删除" onclick="delItem(this)" type="button"><span class="glyphicon glyphicon-remove"></span></button></td>
                                </tr>
                                </tbody>
                            </table>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                    <button type="button" class="btn btn-primary" id="saveSpec">Save</button>
                </div>
            </div>
        </div>
    </div>
    <div style="margin-top: 100px" class="row">
        <div class="col-sm-offset-5 col-sm-10">
            <button style="margin-right: 10px" type="button" class="btn btn-sm btn-primary" onclick="submitTbGoods()"><i class="fa fa-check"></i>保 存
            </button>&nbsp;
            <button type="button" class="btn btn-sm btn-danger" onclick="closeItem()"><i class="fa fa-reply-all"></i>关 闭
            </button>
        </div>
    </div>
</div>


<th:block th:include="include :: footer"/>
<link rel="shortcut icon" href="../../static/ajax/libs/select2/select2.js" th:href="@{select2.js}"/>
<!--<script type="text/javascript" src="../../static/ajax/libs/select2/select2.js"></script>-->
<script th:inline="javascript">


        //给下拉框赋值
    $(function () {
        querySpec();
        //里面装map的数组
        specArray=[];
        //里面装map中key的数组
        specArrayKey=[];
        //里面装map中value的数组
        specArrayValue=[];
        //里面装map中value对应选项图片的数组
        specArrayImg=[];
    })
        //保存规格成功后需要重新异步请求查询规格
        function querySpec(){
            var config = {
                url: "/TbProduct/querySpecList",
                type: "get",
                dataType: "json",
                data: "",
                success: function(data) {
                    if (data.code == web_status.SUCCESS) {
                        specNameList=data.data;
                        $("#specValueList").empty();
                        for (var  i = 0; i < specNameList.length; i++) {
                            $("#specNameList").append(" <option value=\""+specNameList[i].specName+"\">"+specNameList[i].specName+"</option>");
                        }
                    }
                }
            };
            $.ajax(config)
        }
    $('#specNameList').change(function(){
        var specName=$(this).children('option:selected').val();//这就是selected的值

        for (var  i = 0; i < specNameList.length; i++) {
            if (specNameList[i].specName == specName) {
                var values = specNameList[i].specOptionList;
                $("#specValueList").empty();
                for (var j = 0; j < values.length; j++) {
                    $("#specValueList").append(" <option value=\"" + values[j].optionName + "\">" + values[j].optionName + "</option>")
                }
            }
        }
    })

    //二级规格下拉框的值改变
    $('#specValueList').change(function(){
        var thCol=$(this).children('option:selected').val();
        //给表格中加一级select选中的列，给该列的值中赋值二级select选中的值
        var thName=$('#specNameList').children('option:selected').val()
        //找到所屬的當前表格
        //把数据存成map

            //判断一级spec是否在map中存在，存在则只添加二级，不存在则添加map
            if(!isExist(thName)){
                var specOptionList=[];
                //图片再说
                specOptionList.push(thCol);
                var specMap={}
                specMap[thName] = specOptionList;
                specArray.push(specMap)
                specArrayKey.push(thName);
                specArrayValue.push(specOptionList)
            }else{
                //获取map的value，并在value数组中添加二级
                var specOptionList=[];
                for(var i=0;i<specArray.length;i++){
                    //如果map的key相等，则获取该map的值
                    for (var key in specArray[i]) {
                        //同时获取装key的数组和装value的数组
                        if(key==thName){
                            specOptionList=specArray[i][thName]
                            //直接存入
                            specOptionList.push(thCol);
                            //这里不能直接push
                            //specArrayValue[i].push(thCol);
                        }

                    }
                }

            }


        var discartResult=discarts(specArrayValue)
        //判断列名是否存在，不存在新增，
        var th2 ;
        for(var i=0;i<specArrayKey.length;i++){
            th2=$('#'+specArrayKey[i]).length<1;
            if(th2){
                $th = $("<th id='"+specArrayKey[i]+"'>"+specArrayKey[i]+"</th>");
                $("#basic>thead>tr").append($th);
            }
        }
        $("#basic>tbody").empty();
            //增加一行或多行
        if(!Array.isArray(discartResult[0])){
            for(var j=0;j<discartResult.length;j++){
                var $col="<td name='"+specArrayKey[0]+"'>"+discartResult[j]+"</td>";
                var mode_tr = '<tr>\n' +
                    '                    <td><input name="goodsName" placeholder="请输入商品名称" class="form-control" type="text" style="width: 250px" required></td>\n' +
                    '                    <td><input name="costPrice" placeholder="供价" class="form-control" style="width: 80px" type="text"></td>\n' +
                    '                    <td><input name="sellPrice" placeholder="售价" class="form-control" type="text" style="width: 80px" required></td>\n' +
                    '                    <td><input name="inventory" placeholder="库存" class="form-control" type="text" style="width: 80px" required></td>\n' +
                    '                    <td><select name="status" class="form-control" style="width: 80px">\n' +
                    '                        <option value="0">上架</option>\n' +
                    '                        <option value="1">下架</option>\n' +
                    '                        <option value="2">已删除</option>\n' +
                    '                    </select></td><td><img class="img-thumbnail hidden" name="img" src="" style="float: left;width: 55px;height: 40px;"><input type="file" name="file" style="float: left;width:70px;height:40px;margin-top: 10px;" onchange="setImage(this);" /></td>' +
                    ''+$col+'<td><button alt="删除" onclick="delCol(this)" type="button"><span class="glyphicon glyphicon-remove"></span></button></td>\n' +
                    '                </tr>';
                $("#basic>tbody").append(mode_tr);
            }
        }else{
            for(var j=0;j<discartResult.length;j++){
                var $col1="";
                for(var k=0;k<discartResult[j].length;k++){
                    $col1 += "<td name='"+specArrayKey[k]+"'>"+discartResult[j][k]+"</td>";
                }
                //添加一行
                var mode_tr1 = '<tr>\n' +
                    '                    <td><input name="goodsName" placeholder="请输入商品名称" class="form-control" type="text" style="width: 250px" required></td>\n' +
                    '                    <td><input name="costPrice" placeholder="请输入数字" class="form-control" style="width: 100px" type="text" required></td>\n' +
                    '                    <td><input name="sellPrice" placeholder="请输入数字" class="form-control" type="text" style="width: 100px" required></td>\n' +
                    '                    <td><input name="inventory" placeholder="请输入数字" class="form-control" type="text" style="width: 100px" required></td>\n' +
                    '                    <td><select name="status" class="form-control" style="width: 80px">\n' +
                    '                        <option value="0">上架</option>\n' +
                    '                        <option value="1">下架</option>\n' +
                    '                        <option value="2">已删除</option>\n' +
                    '                    </select></td>' +
                    '<td><img class="img-thumbnail hidden" name="img" src="" style="float: left;width: 55px;height: 40px;"><input type="file" name="file" style="float: left;width:70px;height:40px;margin-top: 10px;" onchange="setImage(this);" /></td>' +
                    ''+$col1+'<td><button alt="删除" onclick="delCol(this)" type="button"><span class="glyphicon glyphicon-remove"></span></button></td>\n' +
                    '                </tr>';
                $("#basic>tbody").append(mode_tr1);
            }
        }

    })
        //列名是否存在
        function isExist(thName) {
            for(var i=0;i<specArray.length;i++){
                if(specArray[i][thName]!=null){
                    return true;
                }
            }
            return false;
        }

        //sku算法
        function discarts() {
            //笛卡尔积
            var twodDscartes = function (a, b) {
                var ret = [];
                for (var i = 0; i < a.length; i++) {
                    for (var j = 0; j < b.length; j++) {
                        ret.push(ft(a[i], b[j]));
                    }
                }
                return ret;
            }
            var ft = function (a, b) {
                if (!(a instanceof Array))
                    a = [a];
                var ret = a.slice(0);
                ret.push(b);
                return ret;
            }
            //多个一起做笛卡尔积
            return (function (data) {
                var len = data.length;
                if (len == 0)
                    return [];
                else if (len == 1)
                    return data[0];
                else {
                    var r = data[0];
                    for (var i = 1; i < len; i++) {
                        r = twodDscartes(r, data[i]);
                    }
                    return r;
                }
            })(arguments.length > 1 ? arguments : arguments[0]);
        }

        //移除商品列
        function delCol(element) {
            $(element).parent().parent().remove();
        }
    /*选择产品分类*/
    function selectCategoryTree() {
        var options = {
            title: '选择分类',
            width: "380",
            url: ctx + "categoryController/selectDeptTree/" + $("#treeId").val(),
            callBack: setCategoryValue
        };
        $.modal.openOptions(options);
    }
        function sleep(numberMillis) {
            var now = new Date();
            var exitTime = now.getTime() + numberMillis;
            while (true) {
                now = new Date();
                if (now.getTime() > exitTime)
                    return;
            }
        }
    //提交表单
    function submitTbGoods() {
        if ($.validate.form()) {
        //组装属性信息字符串attrStr要存入扩展属性
        var attrStr = "{";
        for (var i = 0; i < $("#addGoods-attr input").length; i++) {
            attrStr += "\"" +$("#addGoods-attr input")[i].name + "\":\"" +$("#addGoods-attr input")[i].value + "\"";
            if (i < $("#addGoods-attr input").length - 1) {
                attrStr += ",";
            }
        }
        attrStr += "}";
        //获取商品列表信息
        //遍历th获得动态添加的规格名称
        var goodList=[];
        $("#basic tbody tr").each(function (i,e) {
            var goods={};
            goods.goodsName=$(this).find("input[name='goodsName']").val();
            goods.costPrice=$(this).find("input[name='costPrice']").val();
            goods.sellPrice=$(this).find("input[name='sellPrice']").val();
            goods.inventory=$(this).find("input[name='inventory']").val();
            goods.status=$(this).find("select option:selected").val();
            goods.shopId=Number($("select[name='shopId'] option:selected").val());
            //获取图片
            var formData = new FormData();
            var docObj = document.getElementById(goods.goodsName);

            if(docObj!=null){
                formData.append('file',docObj.files[0]);
                //上传图片
                $.ajax({
                    url: ctx + "imgUpload/testUpload",
                    type: 'post',
                    cache: false,
                    data: formData,
                    async: false,
                    processData: false,
                    contentType: false,
                    dataType: "json",
                    success: function (result) {
                        if (result.code == web_status.SUCCESS) {
                            goods.bak1=result.msg;
                        }else{
                            $.modal.alertError(result.msg);
                        }
                    }
                });
            }

            var specInfo=[];
            //这里拼接为json字符串存入goods表的spec_info
            for (var j=0;j<specArrayKey.length;j++){
                var map={};
                var specTh=$(this).find("td[name='"+specArrayKey[j]+"']").get(0).innerText;
                map[specArrayKey[j]]=specTh;
                specInfo.push(map);
            }
            goods.specInfo=JSON.stringify(specInfo);

            goodList.push(goods);
        })
        //获取产品信息
            var product={productName:$("input[name='productName']").val(),
                            subtitle:$("input[name='subtitle']").val(),
                            shopId:Number($("select[name='shopId'] option:selected").val()),
                            afterservice:$("input[name='afterservice']").val(),
                            classify3:$("#treeId").val(),
                            template:$("#templateId").val(),
                            brand:$("select[name='brand'] option:selected").val(),
                            packlist:$("input[name='packlist']").val(),
                            goodsList:goodList,
                            bak1:attrStr
            };

            $.ajax({
                url: ctx + 'TbProduct/addTbProduct',//请求地址
                method: 'post',//请求方式
                contentType: "application/json",
                data: JSON.stringify(product) ,//提交的请求参数，一般为json或者?传参字符串
                dataType: 'json',//是否将响应数据转换为json对象,不添加时，默认是响应数据是字符串类型
                success: function (data) {//响应成功的处理函数，data：返回的响应数据
                    if (data.code == web_status.SUCCESS) {
                        parent.$.modal.msgSuccess(data.msg);
                        closeItem();
                        parent.$.table.refresh();
                    }else{
                        $.modal.alertError(data.msg);
                    }
                }
            });
        }
    }




    //选择分类后给input框赋值
    function setCategoryValue(index, layero) {

        var body = layer.getChildFrame('body', index);
        $("#treeId").val(body.find('#treeId').val());
        $("#treeName").val(body.find('#treeName').val());
        layer.close(index);

        // 根据用户选择的分类id去获取模板属性
        $.ajax({
            url: ctx + 'templateController/getTemplateByCategoryId?categoryId=' + $("#treeId").val(),//请求地址
            method: 'get',//请求参数
            data: {},//提交的请求参数，一般为json或者?传参字符串
            dataType: 'json',//是否将响应数据转换为json对象,不添加时，默认是响应数据是字符串类型
            success: function (template) {//响应成功的处理函数，data：返回的响应数据
                $("#templateId").val(template.templateId);
                // 获取属性并追加在页面中
                getAttribute(template.attribute);
                //给品牌赋值下拉框
                getBrand(template.brands);
            }
        });
    }

    //获取并设置品牌
    function getBrand(brands){
        $("#addGoods-brand").empty();
        var brandsObj=JSON.parse(brands);
        for (var  i = 0; i < brandsObj.length; i++) {
            $("#addGoods-brand").append(" <option value=\""+brandsObj[i].brandId+"\">"+brandsObj[i].brandName+"</option>")
        }
    }



    //获取属性并追加在页面中
    function getAttribute(attribute) {
        var attributes = JSON.parse(attribute);
        var apendStr="<h4 class=\"form-header h4\">属性信息</h4>";
        for (var i=0;i<attributes.length;i++){
            var group=attributes[i].group;
            apendStr+=" <div class=\"row\">\n" +
                "            <div class=\"col-sm-6\">\n" +
                "                <div class=\"form-group\">\n" +
                "                    <label class=\"col-sm-2 control-label \">"+group+"</label>\n" +
                "                    <div class=\"col-sm-10\">\n" +
                "                    </div>\n" +
                "                </div>\n" +
                "            </div>\n" +
                "        </div>"

            for (var j = 0; j < attributes[i].item.length; j=j+2) {

                var t = j + 1;

                apendStr += "  <div class=\"row\">\n" +
                    "            <div class=\"col-sm-6\">\n" +
                    "                <div class=\"form-group\">\n" +
                    "                    <label class=\"col-sm-4 control-label is-required\">"+attributes[i].item[j].name+":</label>\n" +
                    "                    <div class=\"col-sm-8\">\n" +
                    "                        <input name=\""+attributes[i].item[j].name+"\"  class=\"form-control valid\" type=\"text\"\n" +
                    "                               required>\n" +
                    "                    </div>\n" +
                    "                </div>\n" +
                    "            </div>\n" ;
                if (t < attributes[i].item.length) {
                    apendStr += "<div class=\"col-sm-4\">\n" +
                        "                <div class=\"form-group\">\n" +
                        "                    <label class=\"col-sm-4 control-label is-required\">" + attributes[i].item[t].name + ":</label>\n" +
                        "                    <div class=\"col-sm-8\">\n" +
                        "                        <input name=\""+attributes[i].item[t].name+"\"  class=\"form-control valid\" type=\"text\"\n" +
                        "                               required>\n" +
                        "                    </div>\n" +
                        "                </div>\n" +
                        "            </div>\n";
                }
                apendStr +=   "        </div>";
            }

        }

        $("#addGoods-attr").children().remove();
        $("#addGoods-attr").append(apendStr);
    }


    function setImagePreviews(avalue) {
        var docObj = document.getElementById("doc");
        var dd = document.getElementById("dd");
        dd.innerHTML = "";
        var fileList = docObj.files;
        for (var i = 0; i < fileList.length; i++) {
            dd.innerHTML += "<div style='float:left;margin-left: 2px;' > <img id='img" + i + "' class='img-thumbnail' /> </div>";
            var imgObjPreview = document.getElementById("img"+i);
            if (docObj.files && docObj.files[i]) {
                //火狐下，直接设img属性
                imgObjPreview.style.display = 'block';
                imgObjPreview.style.width = '50px';
                imgObjPreview.style.height = '50px';
                //imgObjPreview.src = docObj.files[0].getAsDataURL();
                //火狐7以上版本不能用上面的getAsDataURL()方式获取，需要一下方式
                imgObjPreview.src = window.URL.createObjectURL(docObj.files[i]);
            }
            else {
                //IE下，使用滤镜
                docObj.select();
                var imgSrc = document.selection.createRange().text;
                // alert(imgSrc)
                var localImagId = document.getElementById("img" + i);
                //必须设置初始大小
                localImagId.style.width = "150px";
                localImagId.style.height = "180px";
                //图片异常的捕捉，防止用户修改后缀来伪造图片
                try {
                    localImagId.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
                    localImagId.filters.item("DXImageTransform.Microsoft.AlphaImageLoader").src = imgSrc;
                }
                catch (e) {
                    $.modal.alert("您上传的图片格式不正确，请重新选择!");
                    return false;
                }
                imgObjPreview.style.display = 'none';
                document.selection.empty();
            }
        }
        return true;
        //先把图片上传至七牛云上，返回一个图片的路径，提交表单时将路径传给后台存入数据库
    }

    //打开模态框
    $('#exampleModal').on('show.bs.modal', function (event) {
        var button = $(event.relatedTarget) // Button that triggered the modal
        var recipient = button.data('whatever') // Extract info from data-* attributes
        var modal = $(this)
        modal.find('.modal-title').text('New message to ' + recipient)
        //清空模态框中input的值
        modal.find('.modal-body input').each(function (i,e) {
            $(e).val("");
        })
    })


    //添加规格按钮
    $("#addSpecValue").click(function(){
        var temp='<tr>\n' +
            '\t\t\t\t\t\t<td><input class="form-control" type="text" style="width: 250px" name="specValue" value="" required></td>\n' +
            '\t\t\t\t\t\t<td><button alt="删除" onclick="delItem(this)" type="button"><span class="glyphicon glyphicon-remove"></span></button></td>\n' +
            '\t\t\t\t\t</tr>';
        $("#specTable tbody").append(temp);
    });




    //模态框中点击保存按钮后，将规格名称与规格选项赋值给两个下拉框
    $("#saveSpec").click(function () {
        //if ($.validate.form()) {
            var specOptionList=[];
            //遍历属性及属性值传给后端
        var formData = new FormData();
            $("tbody tr").each(function (i,e) {
                var specValue = $(e).find("td input[name='specValue']");

                var specOption= {};
                    specOption.optionName=$(specValue).val();
                specOptionList.push(specOption);
            })
            specOptionList.shift();
            $('#exampleModal').modal('hide');
            var data={specName:$("#specName").val(),specOptionList:specOptionList};

            var config1 = {
            url: "/TbProduct/addSpecAndOption",
            type: "post",
            contentType:"application/json",
            dataType: "json",
            data: JSON.stringify(data),
            success: function(data) {
                if (data.code == web_status.SUCCESS) {
                    $.modal.msgSuccess(data.msg);
                    querySpec();
                }
            }
        };
        $.ajax(config1)

    })

    function setImage(element) {
        //如果属性值为空，必须先输属性值
        debugger
        var currentFirst=$(element).parent().parent().find('input[name="goodsName"]');
        var value=$(currentFirst).val();
        if(value==""||value==null){
            $.modal.alertWarning("请先输入当前属性值!");
            return false;
        }
        if($("#"+value).length>0)
        {
            $.modal.alertWarning("商品名称重复，请重新输入!");
            return false;
        }
        $(element).attr("id",value);
        var img=$(element).parent().find('img').get(0);
        $(img).attr("id","img"+value);
        var docObj = document.getElementById(value);
        var imgObjPreview = document.getElementById("img"+value);
        if (docObj.files[0]) {
            //火狐下，直接设img属性
            imgObjPreview.src = window.URL.createObjectURL(docObj.files[0]);
            imgObjPreview.classList.remove("hidden");
        }
        return true;
    }


    //删除当前属性值
    function delItem(element){
        $(element).parent().parent().remove();
    }
</script>
</body>
</html>
